package com.ruoyi.rpt.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.rpt.domain.RptDesign;
import com.ruoyi.rpt.mapper.RptDesignMapper;
import com.ruoyi.rpt.service.IRptDesignService;
import com.ruoyi.rpt.utils.SqlExecutor;

/**
 * 报表设计Service业务层处理
 */
@Service
public class RptDesignServiceImpl implements IRptDesignService {
    
    @Autowired
    private RptDesignMapper rptDesignMapper;
    
    @Autowired
    private SqlExecutor sqlExecutor;

    /**
     * 获取报表设计信息
     * 
     * @param reportId 报表ID
     * @return 报表设计信息
     */
    @Override
    public RptDesign selectRptDesignByReportId(Long reportId) {
        return rptDesignMapper.selectRptDesignByReportId(reportId);
    }

    /**
     * 保存报表设计
     * 
     * @param rptDesign 报表设计信息
     * @return 结果
     */
    @Override
    public int saveRptDesign(RptDesign rptDesign) {
        // 查询是否已有设计记录
        RptDesign existingDesign = rptDesignMapper.selectRptDesignByReportId(rptDesign.getReportId());
        
        if (existingDesign != null) {
            // 已有设计，创建新版本
            rptDesign.setDesignVersion(existingDesign.getDesignVersion() + 1);
            rptDesign.setCreateTime(DateUtils.getNowDate());
            return rptDesignMapper.insertRptDesign(rptDesign);
        } else {
            // 首次设计
            rptDesign.setDesignVersion(1);
            rptDesign.setCreateTime(DateUtils.getNowDate());
            return rptDesignMapper.insertRptDesign(rptDesign);
        }
    }

    /**
     * 获取报表设计历史版本
     * 
     * @param reportId 报表ID
     * @return 设计历史版本列表
     */
    @Override
    public List<RptDesign> selectDesignHistory(Long reportId) {
        return rptDesignMapper.selectRptDesignHistory(reportId);
    }

    /**
     * 预览SQL查询
     */
    @Override
    public AjaxResult previewSql(Map<String, Object> params) {
        if (params == null || !params.containsKey("sqlQuery")) {
            throw new ServiceException("SQL查询语句不能为空");
        }
        
        String sqlQuery = (String) params.get("sqlQuery");
        
        if (sqlQuery == null || sqlQuery.trim().isEmpty()) {
            throw new ServiceException("SQL查询语句不能为空");
        }
        
        // 验证SQL安全性
        if (!sqlExecutor.isSafeSql(sqlQuery)) {
            throw new ServiceException("SQL语句包含不安全的操作");
        }
        
        // 限制查询结果数量
        String limitedSql = getLimitedSql(sqlQuery);
        
        try {
            List<Map<String, Object>> data = sqlExecutor.executeQuery(limitedSql);
            
            Map<String, Object> result = new HashMap<>();
            result.put("total", data.size());
            result.put("rows", data);
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            throw new ServiceException("执行SQL查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取限制查询结果数量的SQL
     * 
     * @param sql 原SQL
     * @return 限制结果数量的SQL
     */
    private String getLimitedSql(String sql) {
        // 简单处理，添加LIMIT 100
        String lowerSql = sql.toLowerCase().trim();
        if (lowerSql.contains(" limit ")) {
            return sql;
        } else {
            return sql + " LIMIT 100";
        }
    }
} 